// pages/bind/bind.js
const api = require("../../utils/api.js");
const util = require("../../utils/util.js");
const md5 = require("../../utils/md5.js");
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 提交表单
   */
  formSubmit: function(e) {
    //判断是否有空输入
    this.isblack(e.detail.value.no, "学号");
    this.isblack(e.detail.value.password, "密码");
    this.rightNumber(e.detail.value.no, "学号");

    var that = this;
    var user = {
      no: e.detail.value.no,
      password: md5.md5(e.detail.value.password),
      openid: app.globalData.openid
    };

    //查询学号是否注册过
    util
      .request(
        api.bind,
        {
          user: user
        },
        "POST"
      )
      .then(function(res) {
        if (res.data.code === 101) {
          wx.showToast({
            title: "该[学号]不存在",
            icon: "none",
            duration: 2000
          });
          throw new Error("该[学号]不存在");
        } else if (res.data.code === 102) {
          wx.showToast({
            title: "该[学号]已通过验证",
            icon: "none",
            duration: 2000
          });
          throw new Error("该[学号]已通过验证");
        } else if (res.data.code === 103) {
          wx.showToast({
            title: "[密码]错误",
            icon: "none",
            duration: 2000
          });
          throw new Error("[密码]错误");
        } else {
          wx.showModal({
            content: "验证通过，可前往[个人信息]查看",
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                });
              }
            }
          });
        }
      });
  },

  /**
   * 判断用户输入是否为空
   * @param value  属性值  mes  对应的属性中文名称
   */
  isblack: function(value, meg) {
    if (value === "") {
      wx.showToast({
        title: "[" + meg + "]" + "不能为空",
        icon: "none",
        duration: 1500
      });
      throw new Error("[" + meg + "]" + "不能为空");
    }
  },

  /**
   * 检查位数（11位）
   */
  rightNumber: function(value, meg) {
    if (value.length != 11) {
      wx.showToast({
        title: "请输入11位" + "[" + meg + "]",
        icon: "none",
        duration: 1500
      });
      throw new Error("请输入11位" + "[" + meg + "]");
    }
  },

  /**
   * 只能输入数字
   */
  inputNumber(event) {
    let number = event.detail.value.replace(/\D/g, "").replace(/\s+/g, "");
    return number;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {}
});
